#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:

    int scheduleCourse(vector<vector<int>>& courses) {
        for (auto& it : courses) {
            swap(it[0], it[1]);
        }
        sort(courses.begin(), courses.end());
        priority_queue<int> q;
        int time = 0;
        int ans = 0;
        for (auto it : courses) {
            int x = it[0];
            int y = it[1];
            if (time + y <= x) {
                time += y;
                ans++;
                q.push(y);
            }
            else {
                if (!q.empty() && q.top() > y) {
                    time = time - q.top() + y;
                    q.pop();
                    q.push(y);
                }
            }
        }
        return ans;
    }
};